package com.xxx.rpc.starter;

import java.lang.reflect.Field;

import org.springframework.aop.support.AopUtils;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.BeanCreationException;
import org.springframework.beans.factory.config.BeanPostProcessor;

import com.xxx.rpc.common.annos.Reference;
import com.xxx.rpc.starter.RpcPorperties;



public class StarterBeanPostProcessor implements BeanPostProcessor{
	private RpcPorperties rpcPorperties;
	
	public void setRpcPorperties(RpcPorperties rpcPorperties) {
		this.rpcPorperties = rpcPorperties;
	}

	@Override
	public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
		Class<?> objClz;
		if (AopUtils.isAopProxy(bean)) {
			objClz = AopUtils.getTargetClass(bean);
		} else {
			objClz = bean.getClass();
		}
		try {
			for (Field field : objClz.getDeclaredFields()) {
				// 判断该字段是否有 RemoteService 注解
				Reference reference = field.getAnnotation(Reference.class);
				if (reference != null) {
					StarterReferenceBeanFactory referenceBeanFactory = StarterReferenceBeanFactory.getConsumerBean(beanName, field.getType(),
							reference,rpcPorperties);
					Object rpcReference = referenceBeanFactory.getObject();
					field.setAccessible(true);
					field.set(bean, rpcReference);
				}
			}
		} catch (Exception e) {
			throw new BeanCreationException(beanName, e);
		}
		return bean;
	}

	@Override
	public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
		return bean;
	}

}
